<template>
	<div class="book-borrowing page animate__animated animate__fadeInRight">
		<div class="search-container">
			<div class="left-main">
				<el-form ref="queryFormRef" :model="queryForm" inline>
					<el-form-item label="图书状态：" prop="returnStatus">
						<el-select
							v-model="queryForm.returnStatus"
							placeholder="请选择图书状态"
							style="width: 240px;"
							@change="handelSearch"
						>
						<el-option
							:key="0"
							label="已归还"
							:value="Number(0)"
						/>
						<el-option
							:key="1"
							label="未归还"
							:value="Number(1)"
						/>
						</el-select>
					</el-form-item>
					<el-form-item label="借书人：" prop="borrower">
						<el-input v-model="queryForm.borrower" placeholder="请输入借书人"></el-input>
					</el-form-item>
					<el-form-item label="借阅书名：" prop="bookName">
						<el-input v-model="queryForm.bookName" placeholder="请输入借阅书名"></el-input>
					</el-form-item>
					
				</el-form>
			</div>
			<div class="right-main">
				<el-button type="info" icon="RefreshRight" @click="handelResetQueryForm(queryFormRef)">重置</el-button>
				<el-button type="primary" icon="Search" @click="handelSearch">搜索</el-button>
			</div>
		</div>
		<div class="option-container">
			<el-button type="primary" icon="Plus" @click="handelAdd">借阅</el-button>
		</div>
		<div class="data-container">
			<el-table :data="dataList" stripe style="width: 100%" height="100%" @selection-change="(val) => handleSelectionChange(val, 'categoryId')">
				<el-table-column type="selection" width="55" />
                <el-table-column prop="recordId" label="编码" align="center"  width="55"/>
                <el-table-column prop="borrower" label="借书人" align="center" /> 
				<el-table-column prop="phone" label="联系方式" align="center" ></el-table-column>
				<el-table-column prop="book" label="图书名称" align="center" > 
					<template #default="scope">
						<el-tag>{{ scope.row.book?.bookName }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="book" label="图书状态" align="center" > 
					<template #default="scope">
						<el-tag :type="scope.row.book?.isBorrowed?'danger':'success'">
							{{ scope.row.book?.isBorrowed?'借出':'在库' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="borrowDate" label="借书日期" align="center" />
				<el-table-column prop="oughtReturnDate" label="应还日期" align="center" />
				<el-table-column prop="returnDate" v-if="queryForm.returnStatus==0" label="实际归还日期" align="center"></el-table-column>
                <el-table-column label="操作" align="center" fiexd="right" width="300" v-if="queryForm.returnStatus==1">
                    <template #default="scope">
						<el-button
							v-if="scope.row.returnDate==null"
                            type="success"
                            size="small"
                            @click="handelReturn(scope.row)"
                            >归还</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
		</div>
		<div class="page-container">
			<el-pagination
                v-model:current-page="queryForm.pageNo"
                v-model:page-size="queryForm.pageSize"
                :page-sizes="[5, 10, 15, 20, 30]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalcount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
		</div>
		<!-- 弹框 -->
		<el-dialog
			v-model="dialogConfig.show"
			:title="dialogConfig.title"
			width="500"
			draggable
			append-to-body
		>
			<div class="form-main">
				<el-form :model="submitForm" ref="submitFormRef" :rules="submitFormRules" label-width="120px">
					<el-form-item label="图书名称：" prop="bookName" style="display: flex;flex-wrap: nowrap;">
						<el-input v-if="submitForm.bookName" v-model="submitForm.bookName" disabled placeholder="请输入图书名称"></el-input>
						<el-button v-else :icon="Search" @click="chooseBookDialogVisible = true">选择图书</el-button>
					</el-form-item>
					<el-form-item label="借书人：" prop="borrower">
						<el-input v-model="submitForm.borrower" placeholder="请输入借书人"></el-input>
					</el-form-item>
					<el-form-item label="联系方式：" prop="phone">
						<el-input v-model="submitForm.phone" placeholder="请输入借书人联系方式"></el-input>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handelCloseDialog(submitFormRef)">取消</el-button>
					<el-button type="primary" @click="handelSubmitForm(submitFormRef)">
						提交
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog
			v-model="chooseBookDialogVisible"
			title="图书选择"
			width="80vw"
			draggable
			append-to-body
		>
			<div class="choosebook-page" v-if="chooseBookDialogVisible" style="height: 60vh;">
				<books-choose @ChooseBook="handelChooseBook" v-if="chooseBookDialogVisible"></books-choose>
			</div>
		</el-dialog>
		
	</div>
</template>
<script setup>
// 引入通用增删改查模块
import { usePagesOption } from '@/hooks/usePagesOption'
import { getBorrowRecordByPage} from '@/http/apis/bookBorrowing'
import { getBookTypeAll } from '@/http/apis/bookTypeManage'
import { ref, onMounted } from 'vue'
import booksChoose from '@/components/booksChoose.vue'
import { Search } from '@element-plus/icons-vue'
import { borrowBook, returnBook } from '@/http/apis/bookBorrowing'
import { ElMessage,ElMessageBox } from 'element-plus'

// 选择图书的弹窗是否显示
const chooseBookDialogVisible = ref(false)
// 图书类别列表
const bookTypeList = ref([])
// 查询表单
const pageQueryForm = {
	// 借书人
	borrower: '',
	// 借阅的书名称
	bookName: '',
	// 图书状态
	returnStatus:1,
	// 页码
	pageNo:1,
	// 页大小
	pageSize:15,
}
// 借阅表单
const pageSubmitForm = {
	// 图书名称
	bookName: '',
	// 图书ID
	bookId: '',
	// 借书人
	borrower: "",
	// 联系方式
	phone: ''
}
// 借阅表单校验
const pageSubmitFormRules = {
	bookName: [
		{ required: true, message: '请输入图书名称', trigger: 'blur' },
	],
	borrower: [
		{ required: true, message: '请输入借书人', trigger: 'blur' },
	],
	phone: [
		{ required: true, message: '请输入借书人联系方式', trigger: 'blur' },
		{
            pattern: /^1[3456789]\d{9}$|^(1[3456789]\d{3}-?\d{4}-?\d{4})$|^\d{3,4}-\d{7,8}$/,
            message: '请输入正确的联系方式',
            trigger: 'blur'
        }
	],
}
// 初始化控制模块
const {
	// 查询表单
	queryForm,
	// 查询表单的ref
	queryFormRef,
	// 数据列表
	dataList,
	// 借阅表单
	submitForm,
	// 提交表单的REF
	submitFormRef,
	// 借阅表单的ref
	submitFormRules,
	// 弹框配置
	dialogConfig,
	// 数据总数
	totalcount,
	// 重置查询表单
	handelResetQueryForm,
	// 搜索
	handelSearch,
	// 页大小改变
	handleSizeChange,
	// 页码改变
	handleCurrentChange, 
	// 查询数据列表
	featchDataList,
	// 提交表单方法
	handelAdd,
	// 提交表单
	handelSubmitForm,
	// 关闭弹框
	handelCloseDialog,
} = usePagesOption(
	{
		// 查询表单配置项
		pageQueryForm: pageQueryForm,
		// 提交表单
		pageSubmitForm: pageSubmitForm,
		// 提交表单校验
		pageSubmitFormRules: pageSubmitFormRules,
		// 查询数据列表接口
		queryList: getBorrowRecordByPage,
		// 借阅
		addInfo: borrowBook,
	}
)
// 查询图书分类列表
const featchBookTypeList = async () => {
	let res = await getBookTypeAll();
	if (res && res.code === 0) { 
		bookTypeList.value = res.data;
	} else {
		bookTypeList.value = [];
	}
}
// 选择图书
const handelChooseBook = (book) => {
	submitForm.value.bookName = book.bookName;
	submitForm.value.bookId = book.bookId;
	chooseBookDialogVisible.value = false
}
// 归还图书
const handelReturn = async (row) => { 
	ElMessageBox.confirm('是否归还该图书?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		let res = await returnBook({
			recordId: row.recordId
		});
		if (res && res.code === 0) { 
			ElMessage.success('归还成功');
		} else {
			ElMessage.error('归还失败');
		}
		// 刷新列表
		featchDataList();
	}).catch((error) => {
		console.log('error', error)
		ElMessage.info('已取消归还');
	});
}
onMounted(() => {
	// 查询图书分类列表
	featchBookTypeList();
	// 查询数据列表
	featchDataList()
})
</script>